package com.goodbook.community.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;


@Component
// Component表示这是一个通用组件，每一层都能用
public class MailClient {
    private static final Logger logger =  LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

    // 发邮件的人
    @Value("${spring.mail.username}")
    private String from;

    //发邮件方法，参数为：收件人to，主题subject，内容content
    public void sendMail(String to, String subject, String content) {
        try{
            MimeMessage message = mailSender.createMimeMessage();  //createMimeMessage()只提供创建邮件的模板，不负责实现
            MimeMessageHelper helper = new MimeMessageHelper(message);  //MimeMessageHelper是用来帮助构建邮件内容的
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            //如果setText方法不加第二个参数，则默认为普通文本，加了true，说明邮件可以识别html文本
            helper.setText(content, true);
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e)
        {
            logger.error("发送邮件失败： " + e.getMessage());
        }
    }
}
